<template>
  <div class="app-container">
    <el-collapse-transition>
      <el-form v-if="openCondition" :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
        <el-form-item label="隶属组" prop="groupId">
          <el-select v-model="queryParams.groupId" placeholder="请选择隶属组" filterable clearable size="small">
            <el-option
              v-for="dict in groupOptions"
              :key="dict.id"
              :label="dict.theName"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="theName">
          <el-input
            v-model="queryParams.theName"
            placeholder="请输入名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="协议类型" prop="contentType">
          <el-select v-model="queryParams.contentType" placeholder="请选择请求协议类型" clearable size="small">
            <el-option
              v-for="dict in reqContentTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="请求方式" prop="theMethod">
          <el-select v-model="queryParams.theMethod" placeholder="请选择请求方式" clearable size="small">
            <el-option
              v-for="dict in reqHttpMethodOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </el-collapse-transition>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:api:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:api:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:api:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5" style="float: right">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button :type="!openCondition?'success':'info'"
                   :icon="!openCondition?'el-icon-caret-bottom':'el-icon-caret-top'" size="mini"
                   @click="openCondition=!openCondition">{{!openCondition?'展开条件':'收起条件'}}
        </el-button>
      </el-col>
    </el-row>

    <el-table :data="apiList" height="580" @sort-change="handleSortChange" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <!--<el-table-column label="序号" width="50">
        <template scope="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>-->
      <el-table-column label="主键" align="center" sortable="custom" prop="id"/>
      <el-table-column label="隶属组" align="center" sortable="custom" prop="groupId.name"/>
      <el-table-column label="名称" align="center" sortable="custom" prop="theName"/>
      <el-table-column label="请求方式" align="center" sortable="custom" prop="theMethod.value"/>
      <el-table-column label="请求协议类型" align="center" sortable="custom" prop="contentType.value" width="400"/>
      <el-table-column label="请求地址" align="center" sortable="custom" prop="theUrl" :show-overflow-tooltip="true"
                       width="500"/>
      <el-table-column label="操作" align="center" fixed="right" width="180" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-info"
            @click="handleView(scope.row)"
          >详情
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:api:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:api:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改组接口对话框 -->
    <el-dialog :title="title" :visible.sync="open" :close-on-click-modal="false" width="750px">
      <!-- 修改 -->
      <el-form v-if="this.edit" ref="form" :model="form" :rules="rules" label-width="140px">
        <el-form-item label="隶属组" prop="groupId">
          <el-select v-model="form.groupId" filterable placeholder="请选择隶属组">
            <el-option
              v-for="dict in groupOptions"
              :key="dict.id"
              :label="dict.theName"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="theName">
          <el-input v-model="form.theName" placeholder="请输入名称"/>
        </el-form-item>
        <el-form-item label="请求方式" prop="theMethod">
          <el-select v-model="form.theMethod" placeholder="请选择请求方式">
            <el-option
              v-for="dict in reqHttpMethodOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="请求协议类型" prop="contentType">
          <el-select v-model="form.contentType" placeholder="请选择请求协议类型">
            <el-option
              v-for="dict in reqContentTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="请求地址" prop="theUrl">
          <el-input v-model="form.theUrl" type="textarea" placeholder="https://www.baidu.com"/>
        </el-form-item>
        <el-form-item label="Header参数" prop="headerParam">
          <el-input v-model="form.headerParam" type="textarea" placeholder="User-Agent: Mozilla/5.0
Cookie: key=value;"/>
        </el-form-item>
        <el-form-item label="URL参数" prop="urlParam">
          <el-input v-model="form.urlParam" type="textarea" @input="this.paramsCovert" placeholder="key1: value1
key2: value2"/>
        </el-form-item>
        <el-form-item label="Body参数" prop="bodyParam">
          <el-input v-model="form.bodyParam" type="textarea" @input="this.bodyCovert" placeholder="key1: value1
key2: value2"/>
        </el-form-item>
      </el-form>
      <!-- 添加 -->
      <el-form v-if="!this.edit" ref="form" :model="form" :rules="rules" label-width="140px">
        <el-form-item label="隶属组" prop="groupId">
          <el-select v-model="form.groupId" filterable placeholder="请选择隶属组">
            <el-option
              v-for="dict in groupOptions"
              :key="dict.id"
              :label="dict.theName"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="theName">
          <el-input v-model="form.theName" placeholder="请输入名称"/>
        </el-form-item>
        <el-form-item label="请求方式" prop="theMethod">
          <el-select v-model="form.theMethod" placeholder="请选择请求方式">
            <el-option
              v-for="dict in reqHttpMethodOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="请求协议类型" prop="contentType">
          <el-select v-model="form.contentType" placeholder="请选择请求协议类型">
            <el-option
              v-for="dict in reqContentTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="请求地址" prop="theUrl">
          <el-input v-model="form.theUrl" type="textarea" placeholder="https:www.baidu.com"/>
        </el-form-item>
        <el-form-item label="Header参数" prop="headerParam">
          <el-input v-model="form.headerParam" type="textarea" placeholder="User-Agent: Mozilla/5.0
Cookie: key=value;"/>
        </el-form-item>
        <el-form-item label="URL参数" prop="urlParam">
          <el-input v-model="form.urlParam" type="textarea" @input="this.paramsCovert" placeholder="key1: value1
key2: value2"/>
        </el-form-item>
        <el-form-item label="Body参数" prop="bodyParam">
          <el-input v-model="form.bodyParam" type="textarea" @input="this.bodyCovert" placeholder="key1: value1
key2: value2"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" size="mini">确 定</el-button>
        <el-button @click="cancel" size="mini">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 组接口详情 -->
    <el-dialog title="组接口详情" :visible.sync="viewOpen" width="750px">
      <el-form :inline="true" class="detail-inline" label-width="140px">
        <el-form-item label="隶属组：">
          <input class="bird-view-info-input" disabled :title="viewData.groupId && viewData.groupId.name"
                 :value="viewData.groupId && viewData.groupId.name"/>
        </el-form-item>
        <el-form-item label="名称：">
          <input class="bird-view-info-input" disabled :title="viewData.theName" :value="viewData.theName"/>
        </el-form-item>
        <el-form-item label="请求方式：">
          <input class="bird-view-info-input" disabled :title="viewData.theMethod && viewData.theMethod.value"
                 :value="viewData.theMethod && viewData.theMethod.value"/>
        </el-form-item>
        <el-form-item label="请求协议类型：">
          <input class="bird-view-info-input" disabled :title="viewData.contentType && viewData.contentType.value"
                 :value="viewData.contentType && viewData.contentType.value"/>
        </el-form-item>
        <el-form-item style="width: 100%;" label="请求地址：">
          <textarea cols="63" disabled class="bird-view-info-input" type="textarea">{{viewData.theUrl}}</textarea>
        </el-form-item>
        <el-form-item style="width: 100%;" label="Header参数：">
          <textarea cols="63" disabled class="bird-view-info-input" type="textarea">{{viewData.headerParam}}</textarea>
        </el-form-item>
        <el-form-item style="width: 100%;" label="URL参数：">
          <textarea cols="63" disabled class="bird-view-info-input" type="textarea">{{viewData.urlParam}}</textarea>
        </el-form-item>
        <el-form-item style="width: 100%;" label="Body参数：">
          <textarea cols="63" disabled class="bird-view-info-input" type="textarea">{{viewData.bodyParam}}</textarea>
        </el-form-item>
        <el-form-item label="创建人：">
          <input class="bird-view-info-input" disabled :title="viewData.creSb && viewData.creSb.name"
                 :value="viewData.creSb && viewData.creSb.name"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewOpen = false" size="mini">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {addApi, delApi, getApi, listApi, updateApi} from "@/api/system/api";
  import {listGroup} from "@/api/system/group";

  export default {
    data() {
      return {
        // 条件展开
        openCondition: true,
        // 是否修改
        edit: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 组接口表格数据
        apiList: [],
        // 弹出层标题
        title: "",
        // 是否显示详情弹出层
        viewOpen: false,
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          orderByColumn: 'id',
          isAsc: 'desc'
        },
        // 详情参数
        viewData: {},
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          groupId: [
            {required: true, message: "隶属组不能为空", trigger: "blur"}
          ],
          theName: [
            {required: true, message: "名称不能为空", trigger: "blur"}
          ],
          theUrl: [
            {required: true, message: "请输入正确的地址", trigger: "blur", pattern: "[a-zA-z]+://[^\\s]*"}
          ],
          contentType: [
            {required: true, message: "请求协议类型不能为空", trigger: "blur"}
          ],
          theMethod: [
            {required: true, message: "请求方式不能为空", trigger: "blur"}
          ],
          urlParam: [
            {required: false, message: "请输入格式正确的参数", trigger: "blur", pattern: "([^:]+:[^\\n:]+)+"}
          ],
          bodyParam: [
            {required: false, message: "请输入格式正确的参数", trigger: "blur", pattern: "([^:]+:[^\\n:]+)+"}
          ],
          headerParam: [
            {required: false, message: "请输入格式正确的参数", trigger: "blur", pattern: "([^:]+:[^\\n:]+)+"}
          ],
        },
        // 结果匹配模式字典
        groupOptions: [],
        reqContentTypeOptions: [],
        reqHttpMethodOptions: [],
      };
    },
    created() {
      this.getList();
      // 隶属组查询
      const groupParams = {
        pageNum: 1,
        pageSize: 1000,
        orderByColumn: 'id',
        isAsc: 'desc'
      }
      listGroup(groupParams).then(response => {
        this.groupOptions = response.data.list;
      });
      // 请求协议类型
      this.getDicts("ReqContentTypeEnum").then(response => {
        this.reqContentTypeOptions = response.data;
      });
      // 请求方式类型
      this.getDicts("ReqHttpMethodEnum").then(response => {
        this.reqHttpMethodOptions = response.data;
      });
    },
    methods: {
      /** 查询组接口列表 */
      getList() {
        listApi(this.queryParams).then(response => {
          this.apiList = response.data.list;
          this.total = response.data.total;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.resetPropField(this.form);
        this.clearForm('form');
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetPropField(this.queryParams, {pageNum: 1, pageSize: 10, orderByColumn: 'id', isAsc: 'desc'});
        this.handleQuery();
      },
      // 排序改变事件
      handleSortChange(sorter) {
        console.log(sorter)
        this.handleSort(this.queryParams, sorter);
        this.getList();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length != 1
        this.multiple = !selection.length
      },
      /** 详细按钮操作 */
      handleView(row) {
        const id = row.id
        getApi(id).then(response => {
          const {data} = response;
          this.viewData = {
            ...data,
          }
          this.viewOpen = true;
        });
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.edit = false;
        this.open = true;
        this.title = "添加组接口";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.edit = true;
        this.reset();
        const id = row.id || this.ids
        getApi(id).then(response => {
          const {data} = response;
          this.form = {
            ...data,
            theMethod: data.theMethod && data.theMethod.value,
            contentType: data.contentType && data.contentType.value,
            groupId: data.groupId && data.groupId.id
          }
          this.open = true;
          this.title = "修改组接口";
        });
      },
      /** 提交按钮 */
      submitForm: function () {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != undefined) {
              updateApi(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addApi(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      // name=1&age=2  转为key:value
      paramsCovert(value) {
        if (value && value.indexOf('=')) {
          value = value.replace(/&/g, '\n').replace(/=/g, ':')
          this.form.urlParam = value;
        }
      },
      // json  转为key:value
      bodyCovert(value) {
        if (value) {
          try {
            const jsonData = JSON.parse(value);
            let newValue = '';
            for (let key in jsonData) {
              newValue = newValue + key + ':' + jsonData[key] + '\n';
            }
            this.form.bodyParam = newValue;
          } catch (e) {
          }
        }
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除组接口数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delApi(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
      }
    },
  };
</script>
